package com.laker.admin.module.task.core.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.laker.admin.module.sys.entity.SysFile;
import com.laker.admin.module.sys.service.ISysFileService;
import com.laker.admin.module.task.core.IJob;
import com.laker.admin.module.task.core.Job;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import com.laker.admin.config.LakerConfig;
import org.springframework.beans.factory.annotation.Autowired;

@Job(taskCode = "backupmysqljob", taskName = "定期备份mysql数据")
@Slf4j
public class BackupMysqlJob implements IJob {

    @Autowired
    ISysFileService sysFileService;

    @Autowired
    LakerConfig lakerConfig;

    @Override
    public void execute(Map map) throws Exception {
        // 获取当前时间的分钟数
        LocalDateTime now = LocalDateTime.now();
        int minute = now.getMinute();
        if (minute > 2) {
            return;
        }

        log.info("backupmysql job run！" + System.currentTimeMillis());

        // 当前时间 年月日格式
        LocalDate backupbefore = now.toLocalDate();

        // 获取备份开关
        boolean saveFlag = lakerConfig.getBackUp().getSaveFlag();
        String fileFix = lakerConfig.getBackUp().getFileFix();
        // 备份文件名称
        if (saveFlag) {
            String ip = lakerConfig.getBackUp().getIp();
            String username = lakerConfig.getBackUp().getUsername();
            String password = lakerConfig.getBackUp().getPassword();
            String database = lakerConfig.getBackUp().getDatabase();

            String fileBeforeName = fileFix + backupbefore.toString().replaceAll("-", "") + "00.sql";
            File file = circul(0, fileBeforeName);
            file.getParentFile().mkdirs();
            file.createNewFile();

            // 插入数据库
            QueryWrapper<SysFile> wrapper = new QueryWrapper<>();
            wrapper.eq("file_name", fileBeforeName);
            List existsList = sysFileService.list(wrapper);
            if (existsList != null && existsList.size() > 0) {
                // 一天只需要备份一次
            } else {
                String filePath = lakerConfig.getOssFile().getDomain() + File.separator + lakerConfig.getOssFile().getPath() + File.separator + fileBeforeName;
                SysFile sysFile = new SysFile();
                sysFile.setUserId(-1L);
                sysFile.setNickName("job");
                sysFile.setFilePath(filePath);
                sysFile.setFileName(fileBeforeName);
                sysFile.setCreateTime(LocalDateTime.now());
                sysFileService.save(sysFile);
            }


            // 备份数据库
            backup(file, ip, username, password, database);
        }

        // 获取备份开关
        boolean deleteFlag = lakerConfig.getBackUp().getDeleteFlag();
        int deleteDay = lakerConfig.getBackUp().getDeleteDay();
        // 删除多少天前数据库备份文件
        if (deleteFlag) {
            LocalDate before = backupbefore.minusDays(deleteDay);
            String fileBeforeName = fileFix + before.toString().replaceAll("-", "") + "00.sql";
            File file = circul(0, fileBeforeName);
            if (file != null && file.exists()) {
                file.delete();
            }

            // 删除
            QueryWrapper<SysFile> wrapper = new QueryWrapper<>();
            wrapper.eq("file_name", fileBeforeName);
            sysFileService.remove(wrapper);
        }

        log.info("backupmysql job end！" + System.currentTimeMillis());
    }

    private File circul(int i, String fileBeforeName) {
        return new File(new File(lakerConfig.getOssFile().getPath()).getAbsolutePath() + File.separator + fileBeforeName);
    }

    private void backup(File file, String ip, String user, String password, String dbTable) {
        try {
            //要配置好mysql的环境变量，如果链接远程需要注意修改ip地址，还有支持访问端口开通
            Runtime rt = Runtime.getRuntime();
            String command = "mysqldump --single-transaction -h" + ip + " -u" + user + " -p" + password + " --set-charset=utf8 " + dbTable;
            Process child = rt.exec(command);
            InputStream inputStream = child.getInputStream();
            try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);){
                String str;
                while ((str = bufferedReader.readLine()) != null) {
                    outputStreamWriter.write(str + "\r\n");
                }
                outputStreamWriter.flush();}
            inputStream.close();
        } catch (Exception e) {
            log.error("数据库备份错误,错误信息{}", e.getMessage(), e);
            e.printStackTrace();
        }
    }
}
